package com.mine.modules.vm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mine.common.utils.oConvertUtils;
import com.mine.modules.sys.utils.ListUtils;
import com.mine.modules.vm.entity.VmRoleLayer;
import com.mine.modules.vm.entity.VmRolePermission;
import com.mine.modules.vm.mapper.VmRoleLayerMapper;
import com.mine.modules.vm.service.IVmRoleLayerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-15
 */
@Service
public class VmRoleLayerServiceImpl extends ServiceImpl<VmRoleLayerMapper, VmRoleLayer> implements IVmRoleLayerService {

    public void saveRoleLayer(String roleId, String permissionIds, String lastIds) {
        List<String> add = ListUtils.getDiff(lastIds, permissionIds);
        if (add != null && !add.isEmpty()) {
            List<VmRoleLayer> list = new ArrayList<>();
            for (String p : add) {
                if (oConvertUtils.isNotEmpty(p)) {
                    VmRoleLayer vmRoleLayer = lambdaQuery()
                            .eq(VmRoleLayer::getRoleId, roleId)
                            .eq(VmRoleLayer::getLayerId, p).one();
                    if (vmRoleLayer == null) {
                        VmRoleLayer rolePms = new VmRoleLayer(roleId, p);
                        rolePms.setOperateDate(new Date());
                        list.add(rolePms);
                    }
                }
            }
            this.saveBatch(list);
        }
        List<String> delete = ListUtils.getDiff(permissionIds, lastIds);
        if (delete != null && !delete.isEmpty()) {
            for (String layerId : delete) {
                this.remove(new QueryWrapper<VmRoleLayer>().lambda().eq(VmRoleLayer::getRoleId, roleId).eq(VmRoleLayer::getLayerId, layerId));
            }
        }
    }

    @Override
    public List<String> getLayerIdsIdsByRoleIds(List<String> roleIds) {
        return lambdaQuery()
                .in(roleIds != null, VmRoleLayer::getRoleId, roleIds)
                .list()
                .stream()
                .map(VmRoleLayer::getLayerId)
                .collect(Collectors.toList());
    }

}
